﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using MoonLight.LibSocket;
using MoonLight.LibCommon;
using PVAutoTest.LibCommon;
using PVAutoTest.LibDataBase;
using PVAutoTest.TestMngr;

namespace PVAutoTest
{
    public partial class PVAutoTestUi : Form
    {
        public PVAutoTestUi()
        {
            InitializeComponent();
        }

        #region self define funtions
        private void remove_tabpages()
        {
            tabControl1.TabPages.Remove(tabPage_TestSuitViewer);
            tabControl2.TabPages.Remove(tabPage_TCEditor);
        }

        /// <summary>
        /// 获取agm的ip和port
        /// </summary>
        /// <returns></returns>
        private int get_agm_address()
        {
            string ip = "";
            int port = 0;
            ConfigOperator config = new ConfigOperator();
            if (config.GetStrValue("appSettings", "agm_ip", ref ip) < 0)
            {
                Logger.WriteLog("fail to get config of agm_ip");
                return -1;
            }

            if (config.GetIntValue("appSettings", "agm_port", ref port) < 0)
            {
                Logger.WriteLog("fail to get config of agm_port");
                return -1;
            }
            ProjectDefine.AgmIp = ip;
            ProjectDefine.AgmPort = port;
            return 0;
        }

        /// <summary>
        /// 获取DB连接字符串
        /// </summary>
        /// <returns></returns>
        private int get_db_connect_str()
        {
            string conn_str = "";
            ConfigOperator config = new ConfigOperator();
            if (config.GetStrValue("appSettings", "data_source", ref conn_str) < 0)
            {
                Logger.WriteLog("fail to get config of data_source");
                return -1;
            }
            ProjectDefine.ConnStr = "Data Source=" + conn_str;
            return 0;
        }

        /// <summary>
        /// 初始化case树
        /// </summary>
        private void init_tc_tree()
        {
            treeView_TestCase.Nodes.Clear();
            TreeNode root = new TreeNode("TestCases");
            treeView_TestCase.Nodes.Add(root);
            for (int i = 0; i < current_testsuit.GetTestCaseCount(); i++)
            {
                TestData_Event tc_event = current_testsuit.GetTestCaseList()[i].GetEvent();
                TreeNode tc = new TreeNode("CaseNo[" + tc_event.case_no.ToString() + "-" + tc_event.case_sub_no.ToString() + "]");
                tc.Tag = tc_event;
                tc.ToolTipText = "DeviceID = " + tc_event.dev_id + " EventNo = " + tc_event.event_no;
                TreeNode tn_cp_db = new TreeNode("Check DB");
                TreeNode tn_cp_trace = new TreeNode("Check Trace");
                TreeNode tn_cp_log = new TreeNode("Check Log");

                tc.Nodes.Add(tn_cp_db);
                tc.Nodes.Add(tn_cp_trace);
                tc.Nodes.Add(tn_cp_log);

                root.Nodes.Add(tc);
            }
            treeView_TestCase.ExpandAll();
            return;
        }

        /// <summary>
        /// DB Check Points Select All
        /// </summary>
        /// <param name="container"></param>
        private void select_all(Control container)
        {
            for (int i = 0; i < container.Controls.Count; i++)
            {
                //如果是容器类控件 递归调用自己
                if (container.Controls[i].HasChildren)
                {
                    select_all(container.Controls[i]);
                }
                else
                {
                    string name = container.Controls[i].GetType().Name;
                    switch (container.Controls[i].GetType().Name)
                    {
                        case "CheckedListBox":
                            {
                                int count = ((CheckedListBox)(container.Controls[i])).Items.Count;
                                for (int j = 0; j < count; j++)
                                {
                                    ((CheckedListBox)(container.Controls[i])).SetItemChecked(j, true);
                                }
                            }
                            break;
                        default:
                            break;
                    }
                }
            }
        }

        /// <summary>
        /// DB Check Points Select None
        /// </summary>
        /// <param name="container"></param>
        private void select_none(Control container)
        {
            for (int i = 0; i < container.Controls.Count; i++)
            {
                //如果是容器类控件 递归调用自己
                if (container.Controls[i].HasChildren)
                {
                    select_none(container.Controls[i]);
                }
                else
                {
                    string name = container.Controls[i].GetType().Name;
                    switch (container.Controls[i].GetType().Name)
                    {
                        case "CheckedListBox":
                            {
                                int count = ((CheckedListBox)(container.Controls[i])).Items.Count;
                                for (int j = 0; j < count; j++)
                                {
                                    ((CheckedListBox)(container.Controls[i])).SetItemChecked(j, false);
                                }
                            }
                            break;
                        default:
                            break;
                    }
                }
            }
        }

        private void update_db_checkpoint_ui(string case_no_str)
        {
            Logger.WriteLog("update db checkpoint ui for " + case_no_str);

            int start_idx_case_no = case_no_str.IndexOf("[") + 1;
            int end_idx_case_no = case_no_str.IndexOf("-") - 1;
            int start_idx_sub_case_no = case_no_str.IndexOf("-") + 1;
            int end_idx_sub_case_no = case_no_str.IndexOf("]") - 1;

            string case_no = case_no_str.Substring(start_idx_case_no, end_idx_case_no - start_idx_case_no + 1);
            string sub_case_no = case_no_str.Substring(start_idx_sub_case_no, end_idx_sub_case_no - start_idx_sub_case_no + 1);

            //set current db check points to test case
            for (int i = 0; i < current_testsuit.GetTestCaseCount(); i++)
            {
                if (current_testsuit.GetTestCaseList()[i].GetEvent().case_no.ToString() == case_no &&
                    current_testsuit.GetTestCaseList()[i].GetEvent().case_sub_no.ToString() == sub_case_no)
                {
                    current_db_cp = current_testsuit.GetTestCaseList()[i].GetDBCheckPoints();
                }
            }


        }

        private void set_db_checkpoint_event(CheckedListBox listbox)
        {
            for (int i = 0; i < listbox.Items.Count; i++)
            {
                if (listbox.Items[i].ToString() == "MessageNo")
                {
                    current_db_cp.table_event.MessageNo = listbox.GetItemChecked(i);
                }
                else if (listbox.Items[i].ToString() == "EventNo")
                {
                    current_db_cp.table_event.EventNo = listbox.GetItemChecked(i);
                }
                else if (listbox.Items[i].ToString() == "OrgMessage")
                {
                    current_db_cp.table_event.OrgMessage = listbox.GetItemChecked(i);
                }
                else if (listbox.Items[i].ToString() == "DeviceState")
                {
                    current_db_cp.table_event.DeviceState = listbox.GetItemChecked(i);
                }
                else
                {
                    Logger.WriteLog("no checkpoint of " + listbox.Items[i].ToString() + "in table Event");
                }
            }
        }

        private void set_db_checkpoint_componentevent(CheckedListBox listbox)
        {
            for (int i = 0; i < listbox.Items.Count; i++)
            {
                if (listbox.Items[i].ToString() == "ComponentId")
                {
                    current_db_cp.table_componentevent.ComponentId = listbox.GetItemChecked(i);
                }
                else if (listbox.Items[i].ToString() == "CompState")
                {
                    current_db_cp.table_componentevent.CompState = listbox.GetItemChecked(i);
                }
                else
                {
                    Logger.WriteLog("no checkpoint of " + listbox.Items[i].ToString() + "in table ComponentEvent");
                }
            }
        }

        private void set_db_checkpoint_devicefail(CheckedListBox listbox)
        {
            for (int i = 0; i < listbox.Items.Count; i++)
            {
                if (listbox.Items[i].ToString() == "ComponentId")
                {
                    current_db_cp.table_devicefail.ComponentId = listbox.GetItemChecked(i);
                }
                else if (listbox.Items[i].ToString() == "CompFailCount")
                {
                    current_db_cp.table_devicefail.CompFailCount = listbox.GetItemChecked(i);
                }
                else if (listbox.Items[i].ToString() == "Started")
                {
                    current_db_cp.table_devicefail.Started = listbox.GetItemChecked(i);
                }
                else if (listbox.Items[i].ToString() == "Ended")
                {
                    current_db_cp.table_devicefail.Ended = listbox.GetItemChecked(i);
                }
                else if (listbox.Items[i].ToString() == "EventNo")
                {
                    current_db_cp.table_devicefail.EventNo = listbox.GetItemChecked(i);
                }
                else if (listbox.Items[i].ToString() == "State")
                {
                    current_db_cp.table_devicefail.State = listbox.GetItemChecked(i);
                }
                else if (listbox.Items[i].ToString() == "CompState")
                {
                    current_db_cp.table_devicefail.CompState = listbox.GetItemChecked(i);
                }
                else if (listbox.Items[i].ToString() == "StateBit")
                {
                    current_db_cp.table_devicefail.StateBit = listbox.GetItemChecked(i);
                }
                else if (listbox.Items[i].ToString() == "EndEventNo")
                {
                    current_db_cp.table_devicefail.EndEventNo = listbox.GetItemChecked(i);
                }
                else
                {
                    Logger.WriteLog("no checkpoint of " + listbox.Items[i].ToString() + "in table DeviceFail");
                }
            }
        }

        private void set_db_checkpoint_dayfail(CheckedListBox listbox)
        {
            for (int i = 0; i < listbox.Items.Count; i++)
            {
                if (listbox.Items[i].ToString() == "Started")
                {
                    current_db_cp.table_dayfail.Started = listbox.GetItemChecked(i);
                }
                else if (listbox.Items[i].ToString() == "ComponentId")
                {
                    current_db_cp.table_dayfail.ComponentId = listbox.GetItemChecked(i);
                }
                else if (listbox.Items[i].ToString() == "Ended")
                {
                    current_db_cp.table_dayfail.Ended = listbox.GetItemChecked(i);
                }
                else if (listbox.Items[i].ToString() == "EventNo")
                {
                    current_db_cp.table_dayfail.EventNo = listbox.GetItemChecked(i);
                }
                else if (listbox.Items[i].ToString() == "State")
                {
                    current_db_cp.table_dayfail.State = listbox.GetItemChecked(i);
                }
                else if (listbox.Items[i].ToString() == "CompState")
                {
                    current_db_cp.table_dayfail.CompState = listbox.GetItemChecked(i);
                }
                else if (listbox.Items[i].ToString() == "StateBit")
                {
                    current_db_cp.table_dayfail.StateBit = listbox.GetItemChecked(i);
                }
                else
                {
                    Logger.WriteLog("no checkpoint of " + listbox.Items[i].ToString() + "in table DayFail");
                }
            }
        }

        private void set_db_checkpoint_monthfail(CheckedListBox listbox)
        {
            for (int i = 0; i < listbox.Items.Count; i++)
            {
                if (listbox.Items[i].ToString() == "ComponentId")
                {
                    current_db_cp.table_monthfail.ComponentId = listbox.GetItemChecked(i);
                }
                else if (listbox.Items[i].ToString() == "TotalTime")
                {
                    current_db_cp.table_monthfail.TotalTime = listbox.GetItemChecked(i);
                }
                else
                {
                    Logger.WriteLog("no checkpoint of " + listbox.Items[i].ToString() + "in table MonthFail");
                }
            }
        }

        private void set_db_checkpoint_state(CheckedListBox listbox)
        {
            for (int i = 0; i < listbox.Items.Count; i++)
            {
                if (listbox.Items[i].ToString() == "DeviceState")
                {
                    current_db_cp.table_state.DeviceState = listbox.GetItemChecked(i);
                }
                else if (listbox.Items[i].ToString() == "EventCount")
                {
                    current_db_cp.table_state.EventCount = listbox.GetItemChecked(i);
                }
                else if (listbox.Items[i].ToString() == "ExtraEventCount")
                {
                    current_db_cp.table_state.ExtraEventCount = listbox.GetItemChecked(i);
                }
                else
                {
                    Logger.WriteLog("no checkpoint of " + listbox.Items[i].ToString() + "in table State");
                }
            }
        }

        private void set_db_checkpoint_eventfrequency(CheckedListBox listbox)
        {
            for (int i = 0; i < listbox.Items.Count; i++)
            {
                if (listbox.Items[i].ToString() == "Count")
                {
                    current_db_cp.table_eventfrequency.Count = listbox.GetItemChecked(i);
                }
                else
                {
                    Logger.WriteLog("no checkpoint of " + listbox.Items[i].ToString() + "in table EventFrequency");
                }
            }
        }

        private void set_db_checkpoint_openevent(CheckedListBox listbox)
        {
            for (int i = 0; i < listbox.Items.Count; i++)
            {
                if (listbox.Items[i].ToString() == "ComponentId")
                {
                    current_db_cp.table_openevent.ComponentId = listbox.GetItemChecked(i);
                }
                else if (listbox.Items[i].ToString() == "BitNo")
                {
                    current_db_cp.table_openevent.BitNo = listbox.GetItemChecked(i);
                }
                else if (listbox.Items[i].ToString() == "EventNo")
                {
                    current_db_cp.table_openevent.EventNo = listbox.GetItemChecked(i);
                }
                else if (listbox.Items[i].ToString() == "CompState")
                {
                    current_db_cp.table_openevent.CompState = listbox.GetItemChecked(i);
                }
                else if (listbox.Items[i].ToString() == "MessageNo")
                {
                    current_db_cp.table_openevent.MessageNo = listbox.GetItemChecked(i);
                }
                else if (listbox.Items[i].ToString() == "DeviceState")
                {
                    current_db_cp.table_openevent.DeviceState = listbox.GetItemChecked(i);
                }
                else if (listbox.Items[i].ToString() == "OrgMessage")
                {
                    current_db_cp.table_openevent.OrgMessage = listbox.GetItemChecked(i);
                }
                else
                {
                    Logger.WriteLog("no checkpoint of " + listbox.Items[i].ToString() + "in table OpenEvent");
                }
            }
        }

        private void set_db_checkpoint_groupstate(CheckedListBox listbox)
        {
            for (int i = 0; i < listbox.Items.Count; i++)
            {
                if (listbox.Items[i].ToString() == "State")
                {
                    current_db_cp.table_groupstate.State = listbox.GetItemChecked(i);
                }
                else if (listbox.Items[i].ToString() == "EventCount")
                {
                    current_db_cp.table_groupstate.EventCount = listbox.GetItemChecked(i);
                }
                else
                {
                    Logger.WriteLog("no checkpoint of " + listbox.Items[i].ToString() + "in table GroupState");
                }
            }
        }

        private void set_db_checkpoint_componentstate(CheckedListBox listbox)
        {
            for (int i = 0; i < listbox.Items.Count; i++)
            {
                if (listbox.Items[i].ToString() == "CompState")
                {
                    current_db_cp.table_componentstate.CompState = listbox.GetItemChecked(i);
                }
                else
                {
                    Logger.WriteLog("no checkpoint of " + listbox.Items[i].ToString() + "in table ComponentState");
                }
            }
        }

        private void set_db_checkpoint_groupevent(CheckedListBox listbox)
        {
            for (int i = 0; i < listbox.Items.Count; i++)
            {
                if (listbox.Items[i].ToString() == "EventNo")
                {
                    current_db_cp.table_groupevent.EventNo = listbox.GetItemChecked(i);
                }
                else if (listbox.Items[i].ToString() == "OrgMessage")
                {
                    current_db_cp.table_groupevent.OrgMessage = listbox.GetItemChecked(i);
                }
                else if (listbox.Items[i].ToString() == "GroupState")
                {
                    current_db_cp.table_groupevent.GroupState = listbox.GetItemChecked(i);
                }
                else
                {
                    Logger.WriteLog("no checkpoint of " + listbox.Items[i].ToString() + "in table GroupEvent");
                }
            }
        }

        private void set_db_checkpoint_pmresult(CheckedListBox listbox)
        {
            for (int i = 0; i < listbox.Items.Count; i++)
            {
                if (listbox.Items[i].ToString() == "PmId")
                {
                    current_db_cp.table_pmresult.PmId = listbox.GetItemChecked(i);
                }
                else if (listbox.Items[i].ToString() == "Step")
                {
                    current_db_cp.table_pmresult.Step = listbox.GetItemChecked(i);
                }
                else if (listbox.Items[i].ToString() == "TriggerType")
                {
                    current_db_cp.table_pmresult.TriggerType = listbox.GetItemChecked(i);
                }
                else if (listbox.Items[i].ToString() == "Result")
                {
                    current_db_cp.table_pmresult.Result = listbox.GetItemChecked(i);
                }
                else if (listbox.Items[i].ToString() == "State")
                {
                    current_db_cp.table_pmresult.State = listbox.GetItemChecked(i);
                }
                else
                {
                    Logger.WriteLog("no checkpoint of " + listbox.Items[i].ToString() + "in table PmResult");
                }
            }
        }

        private void set_db_checkpoint_event_ui(CheckedListBox listbox, CheckPoint_DB cp_db)
        {
            for (int i = 0; i < listbox.Items.Count; i++)
            {
                if (listbox.Items[i].ToString() == "MessageNo")
                {
                    listbox.SetItemChecked(i, cp_db.table_event.MessageNo);
                }
                else if (listbox.Items[i].ToString() == "EventNo")
                {
                    listbox.SetItemChecked(i, cp_db.table_event.EventNo);
                }
                else if (listbox.Items[i].ToString() == "OrgMessage")
                {
                    listbox.SetItemChecked(i, cp_db.table_event.OrgMessage);
                }
                else if (listbox.Items[i].ToString() == "DeviceState")
                {
                    listbox.SetItemChecked(i, cp_db.table_event.DeviceState);
                }
                else
                {
                    Logger.WriteLog("no checkpoint of " + listbox.Items[i].ToString() + "in table Event");
                }
            }
        }

        private void set_db_checkpoint_componentevent_ui(CheckedListBox listbox, CheckPoint_DB cp_db)
        {
            for (int i = 0; i < listbox.Items.Count; i++)
            {
                if (listbox.Items[i].ToString() == "ComponentId")
                {
                    listbox.SetItemChecked(i, cp_db.table_componentevent.ComponentId);
                }
                else if (listbox.Items[i].ToString() == "CompState")
                {
                    listbox.SetItemChecked(i, cp_db.table_componentevent.CompState);
                }
                else
                {
                    Logger.WriteLog("no checkpoint of " + listbox.Items[i].ToString() + "in table ComponentEvent");
                }
            }
        }

        private void set_db_checkpoint_devicefail_ui(CheckedListBox listbox, CheckPoint_DB cp_db)
        {
            for (int i = 0; i < listbox.Items.Count; i++)
            {
                if (listbox.Items[i].ToString() == "ComponentId")
                {
                    listbox.SetItemChecked(i, cp_db.table_devicefail.ComponentId);
                }
                else if (listbox.Items[i].ToString() == "CompFailCount")
                {
                    listbox.SetItemChecked(i, cp_db.table_devicefail.CompFailCount);
                }
                else if (listbox.Items[i].ToString() == "Started")
                {
                    listbox.SetItemChecked(i, cp_db.table_devicefail.Started);
                }
                else if (listbox.Items[i].ToString() == "Ended")
                {
                    listbox.SetItemChecked(i, cp_db.table_devicefail.Ended);
                }
                else if (listbox.Items[i].ToString() == "EventNo")
                {
                    listbox.SetItemChecked(i, cp_db.table_devicefail.EventNo);
                }
                else if (listbox.Items[i].ToString() == "State")
                {
                    listbox.SetItemChecked(i, cp_db.table_devicefail.State);
                }
                else if (listbox.Items[i].ToString() == "CompState")
                {
                    listbox.SetItemChecked(i, cp_db.table_devicefail.CompState);
                }
                else if (listbox.Items[i].ToString() == "StateBit")
                {
                    listbox.SetItemChecked(i, cp_db.table_devicefail.StateBit);
                }
                else if (listbox.Items[i].ToString() == "EndEventNo")
                {
                    listbox.SetItemChecked(i, cp_db.table_devicefail.EndEventNo);
                }
                else
                {
                    Logger.WriteLog("no checkpoint of " + listbox.Items[i].ToString() + "in table DeviceFail");
                }
            }
        }

        private void set_db_checkpoint_dayfail_ui(CheckedListBox listbox, CheckPoint_DB cp_db)
        {
            for (int i = 0; i < listbox.Items.Count; i++)
            {
                if (listbox.Items[i].ToString() == "Started")
                {
                    listbox.SetItemChecked(i, cp_db.table_dayfail.Started);
                }
                else if (listbox.Items[i].ToString() == "ComponentId")
                {
                    listbox.SetItemChecked(i, cp_db.table_dayfail.ComponentId);
                }
                else if (listbox.Items[i].ToString() == "Ended")
                {
                    listbox.SetItemChecked(i, cp_db.table_dayfail.Ended);
                }
                else if (listbox.Items[i].ToString() == "EventNo")
                {
                    listbox.SetItemChecked(i, cp_db.table_dayfail.EventNo);
                }
                else if (listbox.Items[i].ToString() == "State")
                {
                    listbox.SetItemChecked(i, cp_db.table_dayfail.State);
                }
                else if (listbox.Items[i].ToString() == "CompState")
                {
                    listbox.SetItemChecked(i, cp_db.table_dayfail.CompState);
                }
                else if (listbox.Items[i].ToString() == "StateBit")
                {
                    listbox.SetItemChecked(i, cp_db.table_dayfail.StateBit);
                }
                else
                {
                    Logger.WriteLog("no checkpoint of " + listbox.Items[i].ToString() + "in table DayFail");
                }
            }
        }

        private void set_db_checkpoint_monthfail_ui(CheckedListBox listbox, CheckPoint_DB cp_db)
        {
            for (int i = 0; i < listbox.Items.Count; i++)
            {
                if (listbox.Items[i].ToString() == "ComponentId")
                {
                    listbox.SetItemChecked(i, cp_db.table_monthfail.ComponentId);
                }
                else if (listbox.Items[i].ToString() == "TotalTime")
                {
                    listbox.SetItemChecked(i, cp_db.table_monthfail.TotalTime);
                }
                else
                {
                    Logger.WriteLog("no checkpoint of " + listbox.Items[i].ToString() + "in table MonthFail");
                }
            }
        }

        private void set_db_checkpoint_state_ui(CheckedListBox listbox, CheckPoint_DB cp_db)
        {
            for (int i = 0; i < listbox.Items.Count; i++)
            {
                if (listbox.Items[i].ToString() == "DeviceState")
                {
                    listbox.SetItemChecked(i, cp_db.table_state.DeviceState);
                }
                else if (listbox.Items[i].ToString() == "EventCount")
                {
                    listbox.SetItemChecked(i, cp_db.table_state.EventCount);
                }
                else if (listbox.Items[i].ToString() == "ExtraEventCount")
                {
                    listbox.SetItemChecked(i, cp_db.table_state.ExtraEventCount);
                }
                else
                {
                    Logger.WriteLog("no checkpoint of " + listbox.Items[i].ToString() + "in table State");
                }
            }
        }

        private void set_db_checkpoint_eventfrequency_ui(CheckedListBox listbox, CheckPoint_DB cp_db)
        {
            for (int i = 0; i < listbox.Items.Count; i++)
            {
                if (listbox.Items[i].ToString() == "Count")
                {
                    listbox.SetItemChecked(i, cp_db.table_eventfrequency.Count);
                }
                else
                {
                    Logger.WriteLog("no checkpoint of " + listbox.Items[i].ToString() + "in table EventFrequency");
                }
            }
        }

        private void set_db_checkpoint_openevent_ui(CheckedListBox listbox, CheckPoint_DB cp_db)
        {
            for (int i = 0; i < listbox.Items.Count; i++)
            {
                if (listbox.Items[i].ToString() == "ComponentId")
                {
                    listbox.SetItemChecked(i, cp_db.table_openevent.ComponentId);
                }
                else if (listbox.Items[i].ToString() == "BitNo")
                {
                    listbox.SetItemChecked(i, cp_db.table_openevent.BitNo);
                }
                else if (listbox.Items[i].ToString() == "EventNo")
                {
                    listbox.SetItemChecked(i, cp_db.table_openevent.EventNo);
                }
                else if (listbox.Items[i].ToString() == "CompState")
                {
                    listbox.SetItemChecked(i, cp_db.table_openevent.CompState);
                }
                else if (listbox.Items[i].ToString() == "MessageNo")
                {
                    listbox.SetItemChecked(i, cp_db.table_openevent.MessageNo);
                }
                else if (listbox.Items[i].ToString() == "DeviceState")
                {
                    listbox.SetItemChecked(i, cp_db.table_openevent.DeviceState);
                }
                else if (listbox.Items[i].ToString() == "OrgMessage")
                {
                    listbox.SetItemChecked(i, cp_db.table_openevent.OrgMessage);
                }
                else
                {
                    Logger.WriteLog("no checkpoint of " + listbox.Items[i].ToString() + "in table OpenEvent");
                }
            }
        }

        private void set_db_checkpoint_groupstate_ui(CheckedListBox listbox, CheckPoint_DB cp_db)
        {
            for (int i = 0; i < listbox.Items.Count; i++)
            {
                if (listbox.Items[i].ToString() == "State")
                {
                    listbox.SetItemChecked(i, cp_db.table_groupstate.State);
                }
                else if (listbox.Items[i].ToString() == "EventCount")
                {
                    listbox.SetItemChecked(i, cp_db.table_groupstate.EventCount);
                }
                else
                {
                    Logger.WriteLog("no checkpoint of " + listbox.Items[i].ToString() + "in table GroupState");
                }
            }
        }

        private void set_db_checkpoint_componentstate_ui(CheckedListBox listbox, CheckPoint_DB cp_db)
        {
            for (int i = 0; i < listbox.Items.Count; i++)
            {
                if (listbox.Items[i].ToString() == "CompState")
                {
                    listbox.SetItemChecked(i, cp_db.table_componentstate.CompState);
                }
                else
                {
                    Logger.WriteLog("no checkpoint of " + listbox.Items[i].ToString() + "in table ComponentState");
                }
            }
        }

        private void set_db_checkpoint_groupevent_ui(CheckedListBox listbox, CheckPoint_DB cp_db)
        {
            for (int i = 0; i < listbox.Items.Count; i++)
            {
                if (listbox.Items[i].ToString() == "EventNo")
                {
                    listbox.SetItemChecked(i, cp_db.table_groupevent.EventNo);
                }
                else if (listbox.Items[i].ToString() == "OrgMessage")
                {
                    listbox.SetItemChecked(i, cp_db.table_groupevent.OrgMessage);
                }
                else if (listbox.Items[i].ToString() == "GroupState")
                {
                    listbox.SetItemChecked(i, cp_db.table_groupevent.GroupState);
                }
                else
                {
                    Logger.WriteLog("no checkpoint of " + listbox.Items[i].ToString() + "in table GroupEvent");
                }
            }
        }

        private void set_db_checkpoint_pmresult_ui(CheckedListBox listbox, CheckPoint_DB cp_db)
        {
            for (int i = 0; i < listbox.Items.Count; i++)
            {
                if (listbox.Items[i].ToString() == "PmId")
                {
                    listbox.SetItemChecked(i, cp_db.table_pmresult.PmId);
                }
                else if (listbox.Items[i].ToString() == "Step")
                {
                    listbox.SetItemChecked(i, cp_db.table_pmresult.Step);
                }
                else if (listbox.Items[i].ToString() == "TriggerType")
                {
                    listbox.SetItemChecked(i, cp_db.table_pmresult.TriggerType);
                }
                else if (listbox.Items[i].ToString() == "Result")
                {
                    listbox.SetItemChecked(i, cp_db.table_pmresult.Result);
                }
                else if (listbox.Items[i].ToString() == "State")
                {
                    listbox.SetItemChecked(i, cp_db.table_pmresult.State);
                }
                else
                {
                    Logger.WriteLog("no checkpoint of " + listbox.Items[i].ToString() + "in table PmResult");
                }
            }
        }

        private void set_db_checkpoint()
        {
            set_db_checkpoint_event(checkedListBox_Event);
            set_db_checkpoint_componentevent(checkedListBox_ComponentEvent);
            set_db_checkpoint_devicefail(checkedListBox_DeviceFail);
            set_db_checkpoint_dayfail(checkedListBox_DayFail);

            set_db_checkpoint_monthfail(checkedListBox_MonthFail);
            set_db_checkpoint_state(checkedListBox_State);
            set_db_checkpoint_eventfrequency(checkedListBox_EventFrequency);
            set_db_checkpoint_openevent(checkedListBox_OpenEvent);

            set_db_checkpoint_groupstate(checkedListBox_GroupState);
            set_db_checkpoint_componentstate(checkedListBox_ComponentState);
            set_db_checkpoint_groupevent(checkedListBox_GroupEvent);
            set_db_checkpoint_pmresult(checkedListBox_PmResult);
        }

        private void set_db_checkpoint_ui(CheckPoint_DB cp_db)
        {
            set_db_checkpoint_event_ui(checkedListBox_Event, cp_db);
            set_db_checkpoint_componentevent_ui(checkedListBox_ComponentEvent, cp_db);
            set_db_checkpoint_devicefail_ui(checkedListBox_DeviceFail, cp_db);
            set_db_checkpoint_dayfail_ui(checkedListBox_DayFail, cp_db);

            set_db_checkpoint_monthfail_ui(checkedListBox_MonthFail, cp_db);
            set_db_checkpoint_state_ui(checkedListBox_State, cp_db);
            set_db_checkpoint_eventfrequency_ui(checkedListBox_EventFrequency, cp_db);
            set_db_checkpoint_openevent_ui(checkedListBox_OpenEvent, cp_db);

            set_db_checkpoint_groupstate_ui(checkedListBox_GroupState, cp_db);
            set_db_checkpoint_componentstate_ui(checkedListBox_ComponentState, cp_db);
            set_db_checkpoint_groupevent_ui(checkedListBox_GroupEvent, cp_db);
            set_db_checkpoint_pmresult_ui(checkedListBox_PmResult, cp_db);
        }
        #endregion

        #region delegate function
        /// <summary>
        /// 创建TestSuit后回调此函数，初始化TestCase树
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void CreateTestSuitUi_OnChange(object sender, CreateTestSuitEventArgs e)
        {
            if (!tabControl1.TabPages.Contains(tabPage_TestSuitViewer))
            {
                tabControl1.TabPages.Add(tabPage_TestSuitViewer);
                tabControl1.SelectedTab = tabPage_TestSuitViewer;
            }
            else {
                tabControl1.SelectedTab = tabPage_TestSuitViewer;
            }
            DataTable dt = new DataTable();
            dt.Columns.Add("RunView_CaseNo");
            dt.Columns.Add("RunView_CaseSubNo");
            dt.Columns.Add("RunView_DevId");
            dt.Columns.Add("RunView_EventNo");
            dt.Columns.Add("RunView_EventId");
            dt.Columns.Add("RunView_StartTime");
            dt.Columns.Add("RunView_EndTime");
            dt.Columns.Add("RunView_Result");
            dt.Columns.Add("RunView_Info");
            dt.Columns.Add("RunView_ExpectResult");
            dt.Columns.Add("RunView_ActualResult");
            dataGridView_RunView.DataSource = dt;
            
            current_testsuit = e.GetTestSuit();
            current_db_cp = new CheckPoint_DB();
            init_tc_tree();
        }

        /// <summary>
        /// 每个TestCase运行完后回调此函数，展示运行结果
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void TestCase_OnChange(object sender, TestCaseResultEventArgs e)
        {
            TestCaseResult result = e.GetTestResult();
            
            int row_count = dataGridView_RunView.Rows.Count;
            for (int i = 0; i < row_count; i++) 
            {
                if (e.GetCaseId().ToString() == dataGridView_RunView.Rows[i].Cells["RunView_CaseNo"].Value.ToString() &&
                    e.GetCaseSubNo().ToString() == dataGridView_RunView.Rows[i].Cells["RunView_CaseSubNo"].Value.ToString()) 
                {
                    dataGridView_RunView.Rows[i].Cells["RunView_StartTime"].Value = result.start_time.ToString();
                    dataGridView_RunView.Rows[i].Cells["RunView_EndTime"].Value = result.end_time.ToString();
                    dataGridView_RunView.Rows[i].Cells["RunView_Result"].Value = result.TestResult.ToString();
                    dataGridView_RunView.Rows[i].Cells["RunView_Info"].Value = result.Info.ToString();
                    dataGridView_RunView.Rows[i].Cells["RunView_ExpectResult"].Value = result.expect_result.ToString();
                    dataGridView_RunView.Rows[i].Cells["RunView_ActualResult"].Value = result.actual_result.ToString();
                    if (result.TestResult == ProjectDefine.TCResult_e.TC_PASSED)
                    {
                        dataGridView_RunView.Rows[i].DefaultCellStyle.BackColor = Color.GreenYellow;
                    }
                    else if (result.TestResult == ProjectDefine.TCResult_e.TC_FAILED)
                    {
                        dataGridView_RunView.Rows[i].DefaultCellStyle.BackColor = Color.Red;
                    }
                    else if (result.TestResult == ProjectDefine.TCResult_e.TC_ERROR)
                    {
                        dataGridView_RunView.Rows[i].DefaultCellStyle.BackColor = Color.Yellow;
                    }
                    else {
                        dataGridView_RunView.Rows[i].DefaultCellStyle.BackColor = Color.Gray;
                    }
                }
            }
        }
        #endregion

        #region Common
        private void PVAutoTestUi_Load(object sender, EventArgs e)
        {
            Logger.WriteLog("PVAutoTest start...");
            remove_tabpages();
            if (get_agm_address() < 0) {
                Logger.WriteLog("fail to get agm address");
                MessageBox.Show("fail to get agm address, check configuration");
                this.Close();
            }
            if (get_db_connect_str() < 0) {
                Logger.WriteLog("fail to get DB conn_str");
                MessageBox.Show("fail to get DB connection string, check configuration");
                this.Close();
            }
        }

        /// <summary>
        /// 双击删除当前tab
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tabControl1_DoubleClick(object sender, EventArgs e)
        {
            if (tabControl1.SelectedIndex == 0)
                return;
            ProjectDefine.clear_values(tabControl1.TabPages[tabControl1.SelectedIndex]);
            tabControl1.TabPages.Remove(tabControl1.SelectedTab);
        }

        /// <summary>
        /// 导入TestSuit工程
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void testSuit_iToolStripMenuItem_Click(object sender, EventArgs e)
        {
            openFileDialog_Import.Filter = "Xml files(*.xml)|*.xml";
            openFileDialog_Import.FileName = null;

            if (openFileDialog_Import.ShowDialog() == DialogResult.OK)
            {
                XmlOperator xml_op = new XmlOperator();
                string path = openFileDialog_Import.FileName;
                current_testsuit = new TestSuit();
                if (xml_op.OpenXml(path, ref current_testsuit) < 0)
                {
                    Logger.WriteLog("open TestData.xml fail");
                    MessageBox.Show("open testsuit fail");
                    return;
                }

                for (int i = 0; i < current_testsuit.GetTestCaseCount(); i++)
                { 
                    current_testsuit.GetTestCaseList()[i].OnChange += new TestCase.Delegate_TestCaseResult(TestCase_OnChange); 
                }

                ConfigOperator config = new ConfigOperator();
                int time_step = 0;
                if (config.GetIntValue("appSettings", "time_step", ref time_step) < 0)
                {
                    Logger.WriteLog("fail to get config of time_step");
                    return;
                }
                current_testsuit.SetTimeStep(time_step);

                string ts_data_path = Directory.GetParent(path).ToString();
                string ts_path = Directory.GetParent(ts_data_path).ToString();
                string ts_result_path = ts_path + @"\TestResult";
                current_testsuit.SetSuitPath(ts_path, ts_data_path, ts_result_path);

                if (!tabControl1.TabPages.Contains(tabPage_TestSuitViewer))
                {
                    tabControl1.TabPages.Add(tabPage_TestSuitViewer);
                    tabControl1.SelectedTab = tabPage_TestSuitViewer;
                }
                else
                {
                    tabControl1.SelectedTab = tabPage_TestSuitViewer;
                }

                DataTable dt = new DataTable();
                dt.Columns.Add("RunView_CaseNo");
                dt.Columns.Add("RunView_CaseSubNo");
                dt.Columns.Add("RunView_DevId");
                dt.Columns.Add("RunView_EventNo");
                dt.Columns.Add("RunView_StartTime");
                dt.Columns.Add("RunView_EndTime");
                dt.Columns.Add("RunView_Result");
                dt.Columns.Add("RunView_Info");
                dt.Columns.Add("RunView_ExpectResult");
                dt.Columns.Add("RunView_ActualResult");
                dataGridView_RunView.DataSource = dt;
                
                current_db_cp = new CheckPoint_DB();
                init_tc_tree();
            }
        }

        /// <summary>
        /// 导入test case电子表格
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void allCasesToolStripMenuItem_Click(object sender, EventArgs e)
        {
            openFileDialog_Import.Filter = "Excel 2010 files(*.xlsx)|*.xlsx";
            openFileDialog_Import.FileName = null;

            if (openFileDialog_Import.ShowDialog() == DialogResult.OK)
            {
                string file_name = openFileDialog_Import.FileName;
                if (file_name == "")
                    return;

                string sheet = "";
                ConfigOperator config = new ConfigOperator();
                if (config.GetStrValue("appSettings", "testcases_sheet", ref sheet) < 0)
                {
                    Logger.WriteLog("fail to get config of sheet name");
                    return;
                }

                ExcelOperator ex_op = new ExcelOperator();
                DataSet ds = new DataSet();
                if (ex_op.OpenExcel(file_name, sheet, ref ds) < 0)
                    return;

                ds.Tables[0].Columns.Add("Times");
                dataGridView1_TCViewr.DataSource = ds.Tables[0];
                int row_count = dataGridView1_TCViewr.Rows.Count;
                for (int i = 0; i < row_count; i++)
                {
                    dataGridView1_TCViewr.Rows[i].Cells["Column_Select"].Value = false;
                    dataGridView1_TCViewr.Rows[i].Cells["Column_Times"].Value = 1;
                    if (i % 2 == 0)
                    {
                        dataGridView1_TCViewr.Rows[i].DefaultCellStyle.BackColor = Color.LightGray;
                    }
                }
                remove_tabpages();
            }
        }

        /// <summary>
        /// 导出TestSuit工程
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void testSuit_eToolStripMenuItem_Click(object sender, EventArgs e)
        {
            XmlOperator xml_op = new XmlOperator();
            if (xml_op.CreateXml(current_testsuit) < 0)
            {
                MessageBox.Show("Export TestSuit Fail");
            }
            else
                MessageBox.Show("Export TestSuit Success");
        }

        /// <summary>
        /// 手册
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void manualToolStripMenuItem_Click(object sender, EventArgs e)
        {
            MessageBox.Show("coming soon...");
        }

        /// <summary>
        /// 关于
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            MessageBox.Show("Any question or advise please contect:\nmeng.li@wincor-nixdorf.com");
        }

        /// <summary>
        /// 退出
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //TODO: save current testsuit project before exit?
            this.Close();
        }
        #endregion

        #region TestCasesViewer
        /// <summary>
        /// 设置每个case运行次数
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dataGridView1_TCViewr_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            if (dataGridView1_TCViewr.Columns[e.ColumnIndex].HeaderText == "Times")
            {
                int result;
                object value = dataGridView1_TCViewr.Rows[e.RowIndex].Cells[e.ColumnIndex].Value;
                string times_str = value == null ? "" : value.ToString();
                if (!int.TryParse(times_str, out result) || result <= 0)
                {
                    //if input is invalid just set it back to default value
                    dataGridView1_TCViewr.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = 1;
                }
            }
        }

        /// <summary>
        /// 点击Times列重新渲染datagridview的颜色
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dataGridView1_TCViewr_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            int row_count = dataGridView1_TCViewr.Rows.Count;
            for (int i = 0; i < row_count; i++)
            {
                dataGridView1_TCViewr.Rows[i].Cells["Column_Select"].Value = false;
                if (i % 2 == 0)
                {
                    dataGridView1_TCViewr.Rows[i].DefaultCellStyle.BackColor = Color.LightGray;
                }
            }
        }

        /// <summary>
        /// case全选
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void radioButton_SelectAll_CheckedChanged(object sender, EventArgs e)
        {
            int row_count = dataGridView1_TCViewr.Rows.Count;
            for (int i = 0; i < row_count; i++)
            {
                dataGridView1_TCViewr.Rows[i].Cells["Column_Select"].Value = true;
            }
        }

        /// <summary>
        /// case全不选
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void radioButton_SelectNone_CheckedChanged(object sender, EventArgs e)
        {
            int row_count = dataGridView1_TCViewr.Rows.Count;
            for (int i = 0; i < row_count; i++)
            {
                dataGridView1_TCViewr.Rows[i].Cells["Column_Select"].Value = false;
            }
        }

        /// <summary>
        /// 创建test suit
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button_CreateSuit_Click(object sender, EventArgs e)
        {
            DataSet ds = new DataSet();
            ds.Tables.Add();
            DataTable dt = (DataTable)dataGridView1_TCViewr.DataSource;
            if (dt == null) {
                MessageBox.Show("Please import case first");
                return;
            }
            for (int i = 0; i < dt.Columns.Count; i++)
            {
                ds.Tables[0].Columns.Add(dt.Columns[i].ColumnName);
            }
            int row_count = dataGridView1_TCViewr.Rows.Count;
            for (int i = 0; i < row_count; i++) {
                if (Convert.ToBoolean(dataGridView1_TCViewr.Rows[i].Cells["Column_Select"].Value) == true) {
                    ds.Tables[0].Rows.Add(dt.Rows[i].ItemArray);
                }
            }
            if (ds.Tables[0].Rows.Count == 0) {
                MessageBox.Show("Please Select TestCase First");
                return;
            }

            ConfigOperator config = new ConfigOperator();
            int time_step = 0;
            if (config.GetIntValue("appSettings", "time_step", ref time_step) < 0)
            {
                Logger.WriteLog("fail to get config of time_step");
                return;
            }
            CreateTestSuitUi ts_ui = new CreateTestSuitUi();
            ts_ui.SetTestSuitCases(ds, time_step, this);
            ts_ui.OnChange += new CreateTestSuitUi.TestSuitCreated(CreateTestSuitUi_OnChange);
            ts_ui.Show();
        }
        #endregion

        #region TestSuitViewer
        /// <summary>
        /// 开始运行cases
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripButton_Start_Click(object sender, EventArgs e)
        {
            current_testsuit.RunSuit();
        }

        /// <summary>
        /// 生成report
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripButton_Report_Click(object sender, EventArgs e)
        {
            DataSet ds = new DataSet();
            ds.Tables.Add();
            DataTable dt = (DataTable)dataGridView_RunView.DataSource;
            for (int i = 0; i < dataGridView_RunView.Columns.Count; i++)
            {
                ds.Tables[0].Columns.Add(dt.Columns[i].ColumnName);
            }
            int row_count = dataGridView_RunView.Rows.Count;
            for (int i = 0; i < row_count; i++)
            {
                ds.Tables[0].Rows.Add(dt.Rows[i].ItemArray);         
            }
            if (ds.Tables[0].Rows.Count == 0) {
                MessageBox.Show("no case to report");
                return;
            }
            string time_expend = string.Format("{0:D4}-{1:D2}-{2:D2}T{3:D2}-{4:D2}-{5:D2}", DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, DateTime.Now.Hour, DateTime.Now.Minute, DateTime.Now.Second);
            string filename = current_testsuit.GetSuitResultPath() + "\\TestReport" + time_expend + ".xlsx";
            ExcelOperator ex_op = new ExcelOperator();
            if (ex_op.CreateExcel(filename, ds) < 0)
            {
                MessageBox.Show("create report fail");
            }
            else {
                MessageBox.Show("create report successful");
            }
        }

        private void checkBox_AllDB_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBox_AllDB.Checked)
            {
                TreeNode root = treeView_TestCase.Nodes[0];
                foreach (TreeNode tn in root.Nodes)
                {
                    tn.Nodes[0].Checked = true;
                }
            }
            else {
                TreeNode root = treeView_TestCase.Nodes[0];
                foreach (TreeNode tn in root.Nodes)
                {
                    tn.Nodes[0].Checked = false;
                }
            }
        }

        private void checkBox_AllTrace_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBox_AllTrace.Checked)
            {
                TreeNode root = treeView_TestCase.Nodes[0];
                foreach (TreeNode tn in root.Nodes)
                {
                    tn.Nodes[1].Checked = true;
                }
            }
            else {
                TreeNode root = treeView_TestCase.Nodes[0];
                foreach (TreeNode tn in root.Nodes)
                {
                    tn.Nodes[1].Checked = false;
                }
            }
        }

        private void checkBox_AllLog_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBox_AllLog.Checked)
            {
                TreeNode root = treeView_TestCase.Nodes[0];
                foreach (TreeNode tn in root.Nodes)
                {
                    tn.Nodes[2].Checked = true;
                }
            }
            else {
                TreeNode root = treeView_TestCase.Nodes[0];
                foreach (TreeNode tn in root.Nodes)
                {
                    tn.Nodes[2].Checked = false;
                }
            }
        }

        private void treeView_TestCase_AfterCheck(object sender, TreeViewEventArgs e)
        {
            if (e.Node.Text.Contains("CaseNo"))
            {
                TestData_Event td_event = (TestData_Event)e.Node.Tag;
                if (e.Node.Checked)
                {
                    if (ts_viewr_row_exist(td_event.case_no.ToString(), td_event.case_sub_no.ToString()))
                        return;
                    DataTable dt = (DataTable)dataGridView_RunView.DataSource;
                    dt.Rows.Add();
                    dt.Rows[dt.Rows.Count - 1]["RunView_CaseNo"] = td_event.case_no.ToString();
                    dt.Rows[dt.Rows.Count - 1]["RunView_CaseSubNo"] = td_event.case_sub_no.ToString();
                    dt.Rows[dt.Rows.Count - 1]["RunView_DevId"] = td_event.dev_id;
                    dt.Rows[dt.Rows.Count - 1]["RunView_EventNo"] = td_event.event_no;
                    dt.Rows[dt.Rows.Count - 1]["RunView_EventId"] = td_event.event_id;

                    //enable this case
                    for (int i = 0; i < current_testsuit.GetTestCaseCount(); i++)
                    {
                        if (td_event.case_no == current_testsuit.GetTestCaseList()[i].GetEvent().case_no && 
                            td_event.case_sub_no == current_testsuit.GetTestCaseList()[i].GetEvent().case_sub_no)
                        {
                            current_testsuit.GetTestCaseList()[i].Enable();
                            break;
                        }
                    }
                }
                else {
                    if (!ts_viewr_row_exist(td_event.case_no.ToString(), td_event.case_sub_no.ToString()))
                        return;
                    for (int i = 0; i < dataGridView_RunView.Rows.Count; i++) {
                        //delete this case from datagridview
                        if (dataGridView_RunView.Rows[i].Cells["RunView_CaseNo"].Value.ToString() == td_event.case_no.ToString() &&
                            dataGridView_RunView.Rows[i].Cells["RunView_CaseSubNo"].Value.ToString() == td_event.case_sub_no.ToString())
                        {
                            dataGridView_RunView.Rows.RemoveAt(i);
                            //disable this case in testsuit
                            for (int j = 0; j < current_testsuit.GetTestCaseCount(); j++)
                            {
                                if (td_event.case_no == current_testsuit.GetTestCaseList()[j].GetEvent().case_no &&
                                    td_event.case_sub_no == current_testsuit.GetTestCaseList()[j].GetEvent().case_sub_no)
                                {
                                    current_testsuit.GetTestCaseList()[j].Disable();
                                    break;
                                }
                            }
                            break;
                        }
                    }
                }
            }
            else if (e.Node.Text.Contains("Check"))
            {
                TestData_Event p_td_event = (TestData_Event)e.Node.Parent.Tag;
                int cp_mask = 0;
                int idx = 0;
                for (int i = 0; i < current_testsuit.GetTestCaseCount(); i++)
                {
                    if (p_td_event.case_no == current_testsuit.GetTestCaseList()[i].GetEvent().case_no &&
                        p_td_event.case_sub_no == current_testsuit.GetTestCaseList()[i].GetEvent().case_sub_no)
                    {
                        cp_mask = current_testsuit.GetTestCaseList()[i].GetCheckPoints();
                        idx = i;
                        break;
                    }
                }
                if (e.Node.Text == "Check DB")
                {
                    if (e.Node.Checked)
                    {
                        cp_mask = cp_mask | (int)ProjectDefine.TCCheckPoints_e.CP_DATABASE;
                    }
                    else
                    {
                        cp_mask = cp_mask & ~((int)ProjectDefine.TCCheckPoints_e.CP_DATABASE);
                    }
                }
                else if (e.Node.Text == "Check Trace")
                {
                    if (e.Node.Checked)
                    {
                        cp_mask = cp_mask | (int)ProjectDefine.TCCheckPoints_e.CP_TRACE;
                    }
                    else
                    {
                        cp_mask = cp_mask & ~((int)ProjectDefine.TCCheckPoints_e.CP_TRACE);
                    }
                }
                else if (e.Node.Text == "Check Log")
                {
                    if (e.Node.Checked)
                    {
                        cp_mask = cp_mask | (int)ProjectDefine.TCCheckPoints_e.CP_LOG;
                    }
                    else
                    {
                        cp_mask = cp_mask & ~((int)ProjectDefine.TCCheckPoints_e.CP_LOG);
                    }
                }
                current_testsuit.GetTestCaseList()[idx].SetCheckPoints(cp_mask);
            }
            else { 
                //click root node
                if (e.Node.Checked)
                {
                    for (int i = 0; i < e.Node.Nodes.Count; i++) {
                        e.Node.Nodes[i].Checked = true;
                    }
                }
                else {
                    for (int i = 0; i < e.Node.Nodes.Count; i++)
                    {
                        e.Node.Nodes[i].Checked = false;
                    }
                }
            }
        }

        private void treeView_TestCase_AfterSelect(object sender, TreeViewEventArgs e)
        {
            if (e.Node.Text.Contains("CaseNo"))
            {
                toolStripLabel_TCNo.Text = e.Node.Text;
                if (!tabControl2.TabPages.Contains(tabPage_TCEditor))
                {
                    tabControl2.TabPages.Add(tabPage_TCEditor);
                    tabControl2.SelectedTab = tabPage_TCEditor;
                }
                else
                {
                    tabControl2.SelectedTab = tabPage_TCEditor;
                }
                ProjectDefine.clear_values(tabPage_TCEditor);
                //update ui
                string case_no_str = toolStripLabel_TCNo.Text;
                int start_idx_case_no = case_no_str.IndexOf("[") + 1;
                int end_idx_case_no = case_no_str.IndexOf("-") - 1;
                int start_idx_sub_case_no = case_no_str.IndexOf("-") + 1;
                int end_idx_sub_case_no = case_no_str.IndexOf("]") - 1;

                string case_no = case_no_str.Substring(start_idx_case_no, end_idx_case_no - start_idx_case_no + 1);
                string sub_case_no = case_no_str.Substring(start_idx_sub_case_no, end_idx_sub_case_no - start_idx_sub_case_no + 1);

                //set current db check points to test case
                CheckPoint_DB db_cp = new CheckPoint_DB();
                for (int i = 0; i < current_testsuit.GetTestCaseCount(); i++)
                {
                    if (current_testsuit.GetTestCaseList()[i].GetEvent().case_no.ToString() == case_no &&
                        current_testsuit.GetTestCaseList()[i].GetEvent().case_sub_no.ToString() == sub_case_no)
                    {
                        db_cp = current_testsuit.GetTestCaseList()[i].GetDBCheckPoints();
                        break;
                    }
                }

                set_db_checkpoint_ui(db_cp);
            }
            else
            {
                if (tabControl2.TabPages.Contains(tabPage_TCEditor))
                {
                    tabControl2.TabPages.Remove(tabPage_TCEditor);
                    tabControl2.SelectedTab = tabPage_TSRunner;
                }
                else
                {
                    tabControl2.SelectedTab = tabPage_TSRunner;
                }
                ProjectDefine.clear_values(tabPage_TCEditor);
            }
        }

        /// <summary>
        /// to check if a row of case_no is already existed 
        /// </summary>
        /// <param name="case_no"></param>
        /// <returns></returns>
        private bool ts_viewr_row_exist(string case_no, string case_subno)
        {
            DataTable dt = (DataTable)dataGridView_RunView.DataSource;
            for (int i = 0; i < dataGridView_RunView.Rows.Count; i++) {
                if (dt.Rows[i]["RunView_CaseNo"].ToString() == case_no &&
                    dt.Rows[i]["RunView_CaseSubNo"].ToString() == case_subno)
                    return true;
            }
            return false;
        }
        #endregion

        #region DB CheckPoints Setting
        private void checkedListBox_Event_SelectedIndexChanged(object sender, EventArgs e)
        {
            //All
            if (checkedListBox_Event.SelectedIndex == 0)
            {
                if (checkedListBox_Event.GetItemChecked(0))
                {
                    for (int i = 0; i < checkedListBox_Event.Items.Count; i++)
                    {
                        checkedListBox_Event.SetItemChecked(i, true);
                    }
                }
                else
                {
                    for (int i = 0; i < checkedListBox_Event.Items.Count; i++)
                    {
                        checkedListBox_Event.SetItemChecked(i, false);
                    }
                }
            }
        }

        private void checkedListBox_ComponentEvent_SelectedIndexChanged(object sender, EventArgs e)
        {
            //All
            if (checkedListBox_ComponentEvent.SelectedIndex == 0)
            {
                if (checkedListBox_ComponentEvent.GetItemChecked(0))
                {
                    for (int i = 0; i < checkedListBox_ComponentEvent.Items.Count; i++)
                    {
                        checkedListBox_ComponentEvent.SetItemChecked(i, true);
                    }
                }
                else
                {
                    for (int i = 0; i < checkedListBox_ComponentEvent.Items.Count; i++)
                    {
                        checkedListBox_ComponentEvent.SetItemChecked(i, false);
                    }
                }
            }
        }

        private void checkedListBox_DeviceFail_SelectedIndexChanged(object sender, EventArgs e)
        {
            //All
            if (checkedListBox_DeviceFail.SelectedIndex == 0)
            {
                if (checkedListBox_DeviceFail.GetItemChecked(0))
                {
                    for (int i = 0; i < checkedListBox_DeviceFail.Items.Count; i++)
                    {
                        checkedListBox_DeviceFail.SetItemChecked(i, true);
                    }
                }
                else
                {
                    for (int i = 0; i < checkedListBox_DeviceFail.Items.Count; i++)
                    {
                        checkedListBox_DeviceFail.SetItemChecked(i, false);
                    }
                }
            }
        }

        private void checkedListBox_DayFail_SelectedIndexChanged(object sender, EventArgs e)
        {
            //All
            if (checkedListBox_DayFail.SelectedIndex == 0)
            {
                if (checkedListBox_DayFail.GetItemChecked(0))
                {
                    for (int i = 0; i < checkedListBox_DayFail.Items.Count; i++)
                    {
                        checkedListBox_DayFail.SetItemChecked(i, true);
                    }
                }
                else
                {
                    for (int i = 0; i < checkedListBox_DayFail.Items.Count; i++)
                    {
                        checkedListBox_DayFail.SetItemChecked(i, false);
                    }
                }
            }
        }

        private void checkedListBox_MonthFail_SelectedIndexChanged(object sender, EventArgs e)
        {
            //All
            if (checkedListBox_MonthFail.SelectedIndex == 0)
            {
                if (checkedListBox_MonthFail.GetItemChecked(0))
                {
                    for (int i = 0; i < checkedListBox_MonthFail.Items.Count; i++)
                    {
                        checkedListBox_MonthFail.SetItemChecked(i, true);
                    }
                }
                else
                {
                    for (int i = 0; i < checkedListBox_MonthFail.Items.Count; i++)
                    {
                        checkedListBox_MonthFail.SetItemChecked(i, false);
                    }
                }
            }
        }

        private void checkedListBox_State_SelectedIndexChanged(object sender, EventArgs e)
        {
            //All
            if (checkedListBox_State.SelectedIndex == 0)
            {
                if (checkedListBox_State.GetItemChecked(0))
                {
                    for (int i = 0; i < checkedListBox_State.Items.Count; i++)
                    {
                        checkedListBox_State.SetItemChecked(i, true);
                    }
                }
                else
                {
                    for (int i = 0; i < checkedListBox_State.Items.Count; i++)
                    {
                        checkedListBox_State.SetItemChecked(i, false);
                    }
                }
            }
        }

        private void checkedListBox_EventFrequency_SelectedIndexChanged(object sender, EventArgs e)
        {
            //All
            if (checkedListBox_EventFrequency.SelectedIndex == 0)
            {
                if (checkedListBox_EventFrequency.GetItemChecked(0))
                {
                    for (int i = 0; i < checkedListBox_EventFrequency.Items.Count; i++)
                    {
                        checkedListBox_EventFrequency.SetItemChecked(i, true);
                    }
                }
                else
                {
                    for (int i = 0; i < checkedListBox_EventFrequency.Items.Count; i++)
                    {
                        checkedListBox_EventFrequency.SetItemChecked(i, false);
                    }
                }
            }
        }

        private void checkedListBox_OpenEvent_SelectedIndexChanged(object sender, EventArgs e)
        {
            //All
            if (checkedListBox_OpenEvent.SelectedIndex == 0)
            {
                if (checkedListBox_OpenEvent.GetItemChecked(0))
                {
                    for (int i = 0; i < checkedListBox_OpenEvent.Items.Count; i++)
                    {
                        checkedListBox_OpenEvent.SetItemChecked(i, true);
                    }
                }
                else
                {
                    for (int i = 0; i < checkedListBox_OpenEvent.Items.Count; i++)
                    {
                        checkedListBox_OpenEvent.SetItemChecked(i, false);
                    }
                }
            }
        }

        private void checkedListBox_GroupState_SelectedIndexChanged(object sender, EventArgs e)
        {
            //All
            if (checkedListBox_GroupState.SelectedIndex == 0)
            {
                if (checkedListBox_GroupState.GetItemChecked(0))
                {
                    for (int i = 0; i < checkedListBox_GroupState.Items.Count; i++)
                    {
                        checkedListBox_GroupState.SetItemChecked(i, true);
                    }
                }
                else
                {
                    for (int i = 0; i < checkedListBox_GroupState.Items.Count; i++)
                    {
                        checkedListBox_GroupState.SetItemChecked(i, false);
                    }
                }
            }
        }

        private void checkedListBox_ComponentState_SelectedIndexChanged(object sender, EventArgs e)
        {
            //All
            if (checkedListBox_ComponentState.SelectedIndex == 0)
            {
                if (checkedListBox_ComponentState.GetItemChecked(0))
                {
                    for (int i = 0; i < checkedListBox_ComponentState.Items.Count; i++)
                    {
                        checkedListBox_ComponentState.SetItemChecked(i, true);
                    }
                }
                else
                {
                    for (int i = 0; i < checkedListBox_ComponentState.Items.Count; i++)
                    {
                        checkedListBox_ComponentState.SetItemChecked(i, false);
                    }
                }
            }
        }

        private void checkedListBox_GroupEvent_SelectedIndexChanged(object sender, EventArgs e)
        {
            //All
            if (checkedListBox_GroupEvent.SelectedIndex == 0)
            {
                if (checkedListBox_GroupEvent.GetItemChecked(0))
                {
                    for (int i = 0; i < checkedListBox_GroupEvent.Items.Count; i++)
                    {
                        checkedListBox_GroupEvent.SetItemChecked(i, true);
                    }
                }
                else
                {
                    for (int i = 0; i < checkedListBox_GroupEvent.Items.Count; i++)
                    {
                        checkedListBox_GroupEvent.SetItemChecked(i, false);
                    }
                }
            }
        }

        private void checkedListBox_PmResult_SelectedIndexChanged(object sender, EventArgs e)
        {
            //All
            if (checkedListBox_PmResult.SelectedIndex == 0)
            {
                if (checkedListBox_PmResult.GetItemChecked(0))
                {
                    for (int i = 0; i < checkedListBox_PmResult.Items.Count; i++)
                    {
                        checkedListBox_PmResult.SetItemChecked(i, true);
                    }
                }
                else
                {
                    for (int i = 0; i < checkedListBox_PmResult.Items.Count; i++)
                    {
                        checkedListBox_PmResult.SetItemChecked(i, false);
                    }
                }
            }
        }

        private void toolStripButton_SelectAll_Click(object sender, EventArgs e)
        {
            select_all(tableLayoutPanel_DB_CheckPoints);
        }

        private void toolStripButton_SelectNone_Click(object sender, EventArgs e)
        {
            select_none(tableLayoutPanel_DB_CheckPoints);
        }

        private void toolStripButton_Save_Click(object sender, EventArgs e)
        {
            string case_no_str = toolStripLabel_TCNo.Text;
            Logger.WriteLog("save current db check points for " + case_no_str);

            set_db_checkpoint();

            int start_idx_case_no = case_no_str.IndexOf("[") + 1;
            int end_idx_case_no = case_no_str.IndexOf("-") - 1;
            int start_idx_sub_case_no = case_no_str.IndexOf("-") + 1;
            int end_idx_sub_case_no = case_no_str.IndexOf("]") - 1;

            string case_no = case_no_str.Substring(start_idx_case_no, end_idx_case_no - start_idx_case_no + 1);
            string sub_case_no = case_no_str.Substring(start_idx_sub_case_no, end_idx_sub_case_no - start_idx_sub_case_no + 1);

            //set current db check points to test case
            for (int i = 0; i < current_testsuit.GetTestCaseCount(); i++) {
                if (current_testsuit.GetTestCaseList()[i].GetEvent().case_no.ToString() == case_no &&
                    current_testsuit.GetTestCaseList()[i].GetEvent().case_sub_no.ToString() == sub_case_no) 
                {
                    current_testsuit.GetTestCaseList()[i].SetDBCheckPoints(current_db_cp);
                    break;
                }
            }
        }

        private void toolStripButton_Copy_Click(object sender, EventArgs e)
        {
            Logger.WriteLog("copy current db check points");
            set_db_checkpoint();
        }

        private void toolStripButton_Paste_Click(object sender, EventArgs e)
        {
            string case_no_str = toolStripLabel_TCNo.Text;
            Logger.WriteLog("paste current db check points to " + case_no_str);

            int start_idx_case_no = case_no_str.IndexOf("[") + 1;
            int end_idx_case_no = case_no_str.IndexOf("-") - 1;
            int start_idx_sub_case_no = case_no_str.IndexOf("-") + 1;
            int end_idx_sub_case_no = case_no_str.IndexOf("]") - 1;

            string case_no = case_no_str.Substring(start_idx_case_no, end_idx_case_no - start_idx_case_no + 1);
            string sub_case_no = case_no_str.Substring(start_idx_sub_case_no, end_idx_sub_case_no - start_idx_sub_case_no + 1);

            //set current db check points to test case
            for (int i = 0; i < current_testsuit.GetTestCaseCount(); i++)
            {
                if (current_testsuit.GetTestCaseList()[i].GetEvent().case_no.ToString() == case_no &&
                    current_testsuit.GetTestCaseList()[i].GetEvent().case_sub_no.ToString() == sub_case_no)
                {
                    current_testsuit.GetTestCaseList()[i].SetDBCheckPoints(current_db_cp);
                    break;
                }
            }
            //update ui
            set_db_checkpoint_ui(current_db_cp);
        }

        private void toolStripButton_PasteToAll_Click(object sender, EventArgs e)
        {
            Logger.WriteLog("paste current db check points to all cases");
            for (int i = 0; i < current_testsuit.GetTestCaseCount(); i++)
            {
                current_testsuit.GetTestCaseList()[i].SetDBCheckPoints(current_db_cp);
            }
            //update ui
            set_db_checkpoint_ui(current_db_cp);
        }
        #endregion

        private TestSuit current_testsuit;
        private CheckPoint_DB current_db_cp;
        
    }
}
